// 封装一些数学函数
// @author:wangff8@qq.com @date:2024-10-29
library MathUtil

    globals
        // 数学工具专用
        hashtable mathHash = InitHashtable()
    endglobals

    // 将指定实数保留指定小数位数，并返回结果（舍弃：如果本身保留本身小数个数的位数精度有问题，比如0.94，保留2位是0.93）
    function keepDecimal takes real x, integer n returns real
        // local temp = 10 ^ (-n)
        // num = num - num % temp
        return x - ModuloReal(x , Pow(10 , -1*n))
    endfunction
    
    // 获取随机的范围数
    function getHashRandomInt takes integer uid, integer k, integer i returns integer
        local integer pKey = StringHash(I2S(uid) + I2S(k))
        return LoadInteger(mathHash, pKey, i)
    endfunction
    // 使用完要要销毁
    function destroyRandomHash takes integer uid, integer k returns nothing
        local integer pKey = StringHash(I2S(uid) + I2S(k))
        call FlushChildHashtable(mathHash, pKey)
    endfunction

    // 随机指定范围指定个数不重复的数字
    function randomIntToHash takes integer uid, integer k, integer min, integer max returns boolean
        local integer array arr
        local integer i
        local integer mid
        local integer pKey = StringHash(I2S(uid) + I2S(k))
        
        if min > max then
            return false
        endif

        // 初始化存储
        set i = min
        loop
            exitwhen i > max
            call SaveInteger(mathHash, pKey, i, i)
            set i = i + 1
        endloop

        // 打乱顺序
        set i = min
        loop
            exitwhen i >= max
            if GetRandomInt(1, 2) == 1 then
                set mid = LoadInteger(mathHash, pKey, i)
                call SaveInteger(mathHash, pKey, i, LoadInteger(mathHash, pKey, i + 1))
                call SaveInteger(mathHash, pKey, i + 1, mid)
            endif
            set i = i + 1
        endloop

        // 打乱顺序2
        set i = max
        loop
            exitwhen i <= min
            
            set mid = LoadInteger(mathHash, pKey, i)
            call SaveInteger(mathHash, pKey, i, LoadInteger(mathHash, pKey, i - 1))
            call SaveInteger(mathHash, pKey, i - 1, mid)

            set i = i - 1
        endloop
        
        return true
    endfunction

endlibrary
